package com.utils.lib.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.utils.lib.model.UADModel;
import com.utils.lib.utilsview.UMD5Util;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UNewNetwork {
    private static UNewNetwork instance;

    public static UNewNetwork getInstance() {
        if (null == instance)
            return new UNewNetwork();
        return instance;
    }

    private static SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void initAdHttp(final String index, final OnHttpListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> tMap = new HashMap<String, String>();
                String format = timeFormat.format(new Date().getTime());
                tMap.put("f", UConstant.AD_F);
                tMap.put("h", UConstant.AD_H);
                tMap.put("v", UConstant.AD_V);
                tMap.put("market", UConstant.MARKET);
                tMap.put("adType", String.valueOf(index));
                tMap.put("appkey", UConstant.APP_KEY);
                tMap.put("t", format);
                String signature = "";
                try {
                    signature = UMD5Util.getSignature(UMD5Util.getSign(tMap), UConstant.APP_SIGN);
                    tMap.put("sign", signature);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final Request request = new Request.Builder()
                        .url(UConstant.BASE_URL + "?" + getUrlParamsByMap(tMap))
                        .get()//传递请求体
                        .build();
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .addInterceptor(new LogInterceptor())
                        .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                        .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("-------", e.getMessage());
                        if (null != listener) listener.error();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        ResponseBody body = response.body();
                        if (body != null) {
                            String string = body.string();
                            body.close();
                            UADModel userBean = new Gson().fromJson(string, new TypeToken<UADModel>() {
                            }.getType());
                            if (null != listener) listener.succeed(userBean);
                        } else {
                            if (null != listener) listener.error();
                        }
                    }
                });
            }
        }).start();

    }

    public interface OnHttpListener {
        void succeed(UADModel o);

        void error();
    }

    /**
     * 将map转换成url
     *
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, String> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }
}
